<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="layout" content="stmain"/>
  <link rel="stylesheet" href="${resource(dir: 'css', file: 'create.css')}" type="text/css"/>
  <link rel="stylesheet" href="${resource(dir: 'css/custom-theme', file: 'jquery-ui-1.8.18.custom.css')}" type="text/css"/>
  <g:javascript src="jquery-1.7.1.min.js"/>
  <g:javascript src="jquery-ui-1.8.18.custom.min.js"/>
  <g:javascript src="jquery.validate.js"/>
  <g:javascript src="wizard.js"/>
  <title>SimTester - Run a Test</title>
</head>
<body>
  <h2>Run a test case</h2>
  <!-- <p>Choose a test to run</p>-->
  <g:img id="add-test" class="toolboximg" title="Upload new test case" dir="images" file="add.png"/>
  <g:img id="del-test" class="toolboximg" title="Delete Test Case" dir="images" file="Remove.png"/>
  <g:img id="edit-tc" class="toolboximg" title="Edit Test Case" dir="images" file="edit.png"/>
  <g:form name="runform" controller="testRun" action="create">
    <div class="tablepagination">
    <table class="sttable" id="runtable" >
      <thead>
        <tr>
          <th>&nbsp;</th>
          <th>ID</th>
          <g:sortableColumn property="name" title="Name"/>
	      <g:sortableColumn property="type" title="Type"/>
	        <g:each in="${catlist}" var="name">
	   	 		<g:sortableColumn property="${name}" title="${name.capitalize()}"/>
			</g:each>
          <g:sortableColumn property="owner" title="Owner"/>
          <g:sortableColumn property="dateCreated" title="Date Created"/>
        </tr>
      </thead>
      <tbody>
        <g:each in="${testcases}" var="tc" status="i">
          <tr>
            <g:if test="${i == 0}">
              <td><g:radio name="testcase" value="${tc.id}" checked="true"/></td>
            </g:if>
            <g:else>
              <td><g:radio name="testcase" value="${tc.id}"/></td>
            </g:else>
            <td>${tc.id}</td>
            <td>${tc.name}</td>
            <td>${tc.type}</td>
            <g:each in="${catlist}" var="name">
              <g:if test="${tc.findCatValue(name)}">
                <td>${tc.findCatValue(name)}</td>
              </g:if>
              <g:else>
                <td>&nbsp;</td>
              </g:else>
            </g:each>
            <td>${tc.owner.username}</td>
            <td><g:formatDate date="${tc.dateCreated}" format="MM/dd/yyyy HH:mm:ss"/></td>
          </tr>
        </g:each>
      </tbody>
    </table>
	<div class="pagination">
		<g:paginate prev="&#8592; Previous" next="Next &#8594;" maxsteps="2" max="10" controller="testRun" action="create" total="${testcasescount}" />
    </div>
    </div>
    
    <div id="wizard">
      <fieldset>
        <p>Choose a name for your test execution</p><br/>
        <g:textField name="trname"/>
      </fieldset>
      <fieldset>
        <p>Repeat this test by:</p>
        <div id="repeat-choice">
          <div class="choice">
            <g:radio name="repeat" value="count" checked="yes"/> <label for="repeat">Count:</label>
            <div id="count">
              <g:textField name="repeatcount" size="2" value="1"/> times
            </div>
          </div>
          <div class="choice">
            <input type="radio" id="duration-radio" name="repeat" value="duration"/> <label for="duration-radio">Duration:</label>
            <div id="duration">
              <input type="number" name="hours" size="2" value="1"/> hours,
              <input type="number" name="mins" size="2" value="0"/> mins,
              <input type="number" name="secs" size="2" value="0"/> seconds
            </div>
          </div>
        </div>
        <div id="instances-choice">
          Run this test with
          <input type="number" name="users" size="2" value="1"/> users
        </div>
      </fieldset>
    </div>
    <div>
      <input class="button green" name="runtest" type="submit" value="Run"/>
    </div>
  </g:form>
  
  <div id="add-test-dialog" title="Add a new test case">
    <g:uploadForm id="addtestform" name="addtestform" controller="testCase" action="create">
      <div>
        <label>Name*</label><br/>
        <input type="text" name="name" class="required"/>
      </div><br/>
      <div>
        <label>Upload a test script*</label><br/>
        <input type="file" name="script" size="14" class="required"/>
      </div>
      <br/>
      <div>
        <label>Select Test Type</label>
        <g:select id="addtypeselectlist" name="addtypeselectlist" value="" from="${typelist}"/>
      </div>
      <input class="button green" type="submit" value="Add"/>
    </g:uploadForm>
  </div>

  <div id="edit-tc-dialog" title="Edit Test Case">
    <g:form name="editform" controller="testCase" action="update">
      <div id="tcholder" >
        <label>Name</label><br/>
        <input type="text" name="name" />
        <br/><br/>
	    <g:each in="${catlist}" var="name">	
	      <div class="field">
	   	    <label>${name.capitalize()}</label><br/>
            <input type="text" id="cat" name="${name.capitalize()}"/>
          </div>
        </g:each>
	    <label>Type</label><br/>
	    <g:select id="edittypeselectlist" name="type" value="" from="${typelist}"/>
	    <input style="display:none;" name="tcid" value="" />
        <input class="button green" type="submit" value="Update"/>
      </div>
    </g:form>
  </div>
 
  <div id="tc-confirm-dialog" title="Confirmation">
  	<g:form name="confirmationform" controller="testCase" action="delete">
    <div>
   	  <input style="display:none;" name="tcid" value="" />
   	  <label>Are you sure you want to delete this test?</label><br/><br/>
   	  <div>
   	  <label></label><br/>
   	  </div>
   	</div>
   	<input class="button green" type="submit" value="Yes"/>
    </g:form>
  </div>
 
  <g:javascript>
	var cat_list = [];
	var tcname;
    $(document).ready(function() {
      // Disable Run button if no test case is checked
      if ( $("input:radio[name=testcase]:checked").length <= 0 )
        disableRunButton();
      else{
        enableRunButton();
        viewTestCase($("input:radio[name=testcase]:checked").val());
      }
        
      $("input:radio[name=testcase]").click(function() {
        if ( $("input:radio[name=testcase]:checked").length > 0 ){
          enableRunButton();
          viewTestCase($("input:radio[name=testcase]:checked").val());
        } else {
          disableRunButton();
        }
      });

      $("#add-test-dialog input[value=Add]").hide();
      $("#edit-tc-dialog input[value=Update]").hide();
      $("#tc-confirm-dialog input[value=Yes]").hide();
	  $("#mng-cat-dialog input[value=Done]").hide();

      function viewTestCase(tcId){
        $.getJSON('/server/query/testcase/' + tcId, function(data){
          if(!$("pre").length){
            $('#runform').after('<h4></h4><pre class="textblock"></pre>');
          }
          $('h4').text(data.name);
          $('pre').text(data.script);
        });
      }

      function enableRunButton() {
        $("input[value=Run]")
          .fadeTo(0, 1)
          .attr('disabled', false)
          .removeClass('disabled')
          .unbind('click')
          .click(function(e) {
            $("#wizard").wizard("open");
            e.preventDefault();
         });

        $("input[value=Edit]")
          .fadeTo(0, 1)
          .attr('disabled', false)
          .removeClass('disabled')
          .unbind('click')
          .click(function() {
            $("input[name=tcid]").val($("input[name=testcase]:checked").val());
            $("#edit-tc-dialog").dialog("open");
          });
      }
      
      function disableRunButton() {
        $("input[value=Run]")
          .fadeTo(0, 0.3)
          .attr('disabled', true)
          .addClass('disabled')
          .unbind('click');
   
   		$("input[value=Remove]")
          .fadeTo(0, 0.3)
          .attr('disabled', true)
          .addClass('disabled')
          .unbind('click');
   
   		$("input[value=Edit]")
          .fadeTo(0, 0.3)
          .attr('disabled', true)
          .addClass('disabled')
          .unbind('click');
      };
      
      // Add test dialog
      $("#add-test-dialog").dialog({
        autoOpen: false,
        width: 350,
        modal: true,
        buttons: [
          {
            id: "add-cancel",
            text: "Cancel",
            class: 'red button',
            click: function() {
              $(this).dialog("close");
            }
          },
          {
            id: "add-create",
            text: "Create",
            class: 'green button',
            click: function() {
              $("#add-test-dialog input[value=Add]").click();
            }
          }
        ]
      });

       // Manage Category dialog
      $("#mng-cat-dialog").dialog({
        autoOpen: false,
        height: 450,
        width: 330,
        modal: true,
        buttons: [
          {
            id: "mng-done",
            text: "Done",
            class: 'green button',
            click: function() {
              $("#mngcatform input[name=updatedcatlist]").val(cat_list);
              $("#mng-cat-dialog input[value=Done]").click();
            }
          }
        ]
      });

      // Edit Test Case Dialog
      $("#edit-tc-dialog").dialog({
        autoOpen: false,
        modal: true,
        buttons: [
          {
            id: "edit-cancel",
            text: "Cancel",
            class: 'red button',
            click: function() {
              $(this).dialog("close");
            }
          },
          {
            id: "edit-update",
            text: "Update",
            class: 'green button',
            click: function() {
			  tcname = $("#edit-tc-dialog input[name=name]").val();
			  if (!tcname) {
			  	tcname = $("input[name=testcase]:checked").parent().next().text();
			  	$("#editform input[name=name]").val(tcname);
			  }
              $("#edit-tc-dialog input[value=Update]").click();
            }
          }
        ]
      });
      
      // Confirmation Delete Test Case Dialog
      $("#tc-confirm-dialog").dialog({
        autoOpen: false,
        height: 200,
        width: 350,
        modal: true,
        buttons: [
          {
            id: "del-no",
            text: "No",
            class: 'red button',
            click: function() {
              $(this).dialog("close");
            }
          },
          {
            id: "del-yes",
            text: "Yes",
            class: 'green button',
            click: function() {
              $("#tc-confirm-dialog input[value=Yes]").click();
            }
          }
        ]
      });
      
      
      $("#add-test").click(function() {
        $("#add-test-dialog").dialog("open");
      });
      
      $("#del-test").click(function(){
        $("#confirmationform div label:eq(1)").html('<b>' + $("input[name=testcase]:checked").parent().next().next().text() + '</b>');
        $("#confirmationform input[name=tcid]").val($("input[name=testcase]:checked").val());
      	$("#tc-confirm-dialog").dialog("open");
      });
      
      $("#mng-cat").click(function() {
        $("#mng-cat-dialog").dialog("open");
        cat_list = [];
		$("#cat-select-list > option").each(function(){
			cat_list.push(this.value);
		}); 
      });
            
      $("#edit-tc").click(function() {
        var id = $("input[name=testcase]:checked").val();
      	$("#editform input[name=tcid]").val(id);
		tcname = '';
      	tcname = $("input[name=testcase]:checked").parent().next().next().text();
   		$("#editform input[name=name]").val(tcname);
   		var tctype = $("input[name=testcase]:checked").parent().next().next().next().text();
   		$("#edittypeselectlist").val(tctype);
      	
		var category = $("input[name=testcase]:checked").closest('tr').find('td').map(function(){
     		return $(this).text();
   		}).get();
		
		var catheader = $("#runtable").find('th').map(function(){
     		return $(this).text();
   		}).get();

		for(var i=2; i < category.length-2; i++){
		  var value = category[i];
		  if(value == '\xa0'){
		    value = '';
		  }
		  $('#tcholder div input[name=' + catheader[i] + ']').val(value);
		}
		
		$("#edit-tc-dialog").dialog("open");       
      });

      $("#mngcatform input[name=add-cat-btn]").click(function(){
          var new_cat_name = $("#catnametxt").val();
		  cat_list.push(new_cat_name);
          $('#cat-select-list').append("<option value='"+new_cat_name+"'>"+new_cat_name+"</option>");
		  $("#catnametxt").val('');
        });
    
        $("#mngcatform input[name=rem-cat-btn]").click(function(){
           $("#cat-select-list option:selected").each( function() {
			 cat_list.splice($.inArray($(this).val(), cat_list),1);
	         $(this).remove();
           });
         });
      
      // Run-test wizard dialog
      var wizdlg = $('#wizard').wizard({
        title: "Execute a test",
        height: 330,
        width: 380,
        finish: function(){
          $("input[value=Run]")
            .unbind('click')
            .click();
        }
      });
      wizdlg.parent().appendTo($("#runform"));
      
      // Radio buttons for test repeat
      $("#duration").hide();
      $("input#repeat").click(function(){
        $("#count").slideDown('fast');
        $("#duration").slideUp('fast');
      });
      $("input#duration-radio").click(function(){
        $("#count").slideUp('fast');
        $("#duration").slideDown('fast');
      });
      
      $("#addtestform").validate({
        errorClass: "validate-error",
        errorElement: "div"
      });
      $("#editform").validate({
        errorClass: "validate-error"
      });
    });
  </g:javascript>
</body>
</html>
